package com.swhy

import com.utils._
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.{SparkConf, SparkContext}
import org.codehaus.jackson.map.ObjectMapper

import java.net.URI
import java.util.UUID


object ChgeProdSaleRptGm {
  def main(args: Array[String]): Unit = {
    if (args.length != 3) {
      println(
        """
          |com.swhy.CompanyInfo
          |params:
          | InputDate    刷数日期
          | OutputPath   输出路径
          | SplitNum     文件生成数量
        """.stripMargin)
      sys.exit()
    }
    val conf = new Configuration()
    val Array(inputDt, outputPath, splitNum) = args
    val sparkConf = new SparkConf().setAppName(this.getClass.getName)
    val sc = new SparkContext(sparkConf)
    val hiveContext = new HiveContext(sc)
    //改下方的sql为需要装换成jason的sql
    val allcompany =
      s"""
      select
      distinct
      '888888' as prod_code,
      '公募定投' as prod_name,
      a.cust_no,
      a.cust_name,
      a.capi_acc,
      nvl(a.mgr_serv,'') as mgr_cd,
      nvl(a.mgr_dev,'') as mgr_dev,
      nvl(a.mgr_sign,'') as mgr_sign,
      nvl(a.brch_org_level_cd_serv,'')  as brch_org_level_cd,
      nvl(a.brch_org_level_cd_dev,'')  as brch_org_level_cd_dev,
      nvl(a.brch_org_level_cd_sign,'')  as brch_org_level_cd_sign,
      nvl(a.brch_org_cd_serv,'')  as brch_org_cd,
      nvl(a.brch_org_cd_dev,'')  as brch_org_cd_dev,
      nvl(a.brch_org_cd_sign,'')  as brch_org_cd_sign,
      a.latest_risk_grad,
      a.cust_grad,
      a.cust_type,
      nvl(round(a.total_asset),0) as total_asset ,
      if(c.asset_acct is null ,'0','1') as prod3_gp_buy,-- 是否购买过股票一年内
      if(e.asset_acct is null ,'0','1') as prod3_is_buy,
      nvl(d.avg_asset_12,0) as prod3_avg_asset_12,-- 一年内日均净资产
      a.latest_risk_grad as prod3_latest_risk_grad,  --风险等级
      cast(b.age as string) as prod3_age,--年龄
      b.edu_degree as prod3_edu_degree,  --学历
      b.career_type_desc as prod3_career,  --职业
      nvl(round(f.xjlzc),0) as prod3_cap_bal,--现金类资产
      nvl(f.xjlzc_mx,'[]')  as prod3_cap_bal_detail--现金类资产明细
      from  app_data.app_dao_acct_info_d_q  a
      left join (SELECT a.cust_id, a.age, b.asset_acct, b.acct_status_cd,a.edu_degree,a.career_type_desc, b.open_acct_dt
                  FROM (SELECT * FROM  sum_data.sum_t98_cust_base_info_k where biz_date =${inputDt}) a
                  JOIN (select *  from app_data.app_adhoc_acct_info_d_q
                        where biz_date =${inputDt} AND acct_status_cd='0000' AND acct_type='普通' )  b
                    ON a.cust_id = b.cust_id) b
      on  a.capi_acc=b.asset_acct
left join (select asset_acct from  sum_data.sum_t98_on_board_match_dtl_z a join pdm_data.pdm_t02_prod_q b on a.prod_id =b.prod_id where trim(prod_type_cd)  in('S00','S10','S30','S20','S22','S01','S11','S31','S21','S36','S21','S32','S33','S34','S35') and a.biz_date>=cast(regexp_replace(add_months(from_unixtime(unix_timestamp('${inputDt}','yyyyMMdd' ),'yyyy-MM-dd'),-12),'-','') as int) and b.biz_date=${inputDt})c
      on   a.capi_acc=c.asset_acct
      left join (SELECT asset_acct, avg(net_asset) as avg_asset_12  FROM  sum_data.sum_t98_asset_acct_info_z  WHERE trim(crdt_acct_flag) = '0'   AND biz_date>=cast(regexp_replace(add_months(from_unixtime(unix_timestamp('${inputDt}','yyyyMMdd' ),'yyyy-MM-dd'),-12),'-','') as int) GROUP BY asset_acct) d
      on a.capi_acc=d.asset_acct
      left join APP_DATA.TEMP_ACCT_CAP_ASSET_BLX_DAOP w
      on  a.capi_acc=w.asset_acct
       left join app_data.app_daop_recmd_aft_purc_z e
      on a.capi_acc=e.asset_acct
      and e.prod_id='公募定投'
      left join app_data.xjlzc_daop_temp  f
      on a.capi_acc=f.asset_acct
      where  a.biz_date=${inputDt}
      """.stripMargin
    print(allcompany)
    val frame  = hiveContext.sql(allcompany)
    val result = frame.rdd.map(x => {
      var cominfo = new StringBuilder()

      val prod_code = x.getAs[String]("prod_code")
      val prod_name = x.getAs[String]("prod_name")
      val capi_acc = x.getAs[String]("capi_acc")
      val cust_no = x.getAs[String]("cust_no")
      val cust_name = x.getAs[String]("cust_name")
      val latest_risk_grad = x.getAs[String]("latest_risk_grad")
      val cust_grad = x.getAs[String]("cust_grad")
      val cust_type = x.getAs[String]("cust_type")
      val mgr_cd = x.getAs[String]("mgr_cd")
      val mgr_dev = x.getAs[String]("mgr_dev")
      val mgr_sign = x.getAs[String]("mgr_sign")
      val brch_org_cd = x.getAs[String]("brch_org_cd")
      val brch_org_cd_dev = x.getAs[String]("brch_org_cd_dev")
      val brch_org_cd_sign = x.getAs[String]("brch_org_cd_sign")
      val brch_org_level_cd = x.getAs[String]("brch_org_level_cd")
      val brch_org_level_cd_dev = x.getAs[String]("brch_org_level_cd_dev")
      val brch_org_level_cd_sign = x.getAs[String]("brch_org_level_cd_sign")

      val prod3_avg_asset_12 =scala.math.BigDecimal(x.getAs[java.math.BigDecimal]("prod3_avg_asset_12"))
      val prod3_avg_asset_121=prod3_avg_asset_12.bigDecimal
      val prod3_cap_bal =scala.math.BigDecimal(x.getAs[java.math.BigDecimal]("prod3_cap_bal"))
      val prod3_cap_bal1=prod3_cap_bal.bigDecimal
      val prod3_cap_bal_detail = x.getAs[String]("prod3_cap_bal_detail")
      val total_asset =scala.math.BigDecimal(x.getAs[java.math.BigDecimal]("total_asset"))
      val total_asset1=total_asset.bigDecimal

      val prod3_gp_buy = x.getAs[String]("prod3_gp_buy")
      val prod3_latest_risk_grad = x.getAs[String]("prod3_latest_risk_grad")
      val prod3_age = x.getAs[String]("prod3_age")
      val prod3_edu_degree = x.getAs[String]("prod3_edu_degree")
      val prod3_career = x.getAs[String]("prod3_career")
      val prod3_is_buy = x.getAs[String]("prod3_is_buy")

      val _id = new ID()
      val index = new Index()
      val companyInfo = new ChgeProdSaleRptGm()

      _id.set_id(UUID.randomUUID().toString)
      index.setIndex(_id)
      companyInfo.setProdCode(prod_code)
      companyInfo.setProdName(prod_name)
      companyInfo.setCapiAcc(capi_acc)
      companyInfo.setCustNo(cust_no)
      companyInfo.setCustName(cust_name)
      companyInfo.setMgrCd(mgr_cd)
      companyInfo.setBrchOrgCd(brch_org_cd)
      companyInfo.setBrchOrgLevelCd(brch_org_level_cd)
      companyInfo.setTotalAsset(total_asset1)
      companyInfo.setProd3CapBal(prod3_cap_bal1)
      companyInfo.setProd3CapBalDetail(prod3_cap_bal_detail)
      companyInfo.setMgrSign(mgr_sign)
      companyInfo.setMgrDev(mgr_dev)
      companyInfo.setBrchOrgCdDev(brch_org_cd_dev)
      companyInfo.setBrchOrgCdSign(brch_org_cd_sign)
      companyInfo.setBrchOrgLevelCdDev(brch_org_level_cd_dev)
      companyInfo.setBrchOrgLevelCdSign(brch_org_level_cd_sign)

      companyInfo.setLatestRiskGrad(latest_risk_grad)
      companyInfo.setCustGrad(cust_grad)
      companyInfo.setCustType(cust_type)
      companyInfo.setMgrDev(mgr_dev)
      companyInfo.setMgrSign(mgr_sign)
      companyInfo.setProd3GpBuy(prod3_gp_buy)
      companyInfo.setProd3AvgAsset12(prod3_avg_asset_121)
      companyInfo.setProd3LatestRiskGrad(prod3_latest_risk_grad)
      companyInfo.setProd3Age(prod3_age)
      companyInfo.setProd3EduDegree(prod3_edu_degree)
      companyInfo.setProd3Career(prod3_career)
      companyInfo.setProd3IsBuy(prod3_is_buy)

      val mapper = new ObjectMapper()

      val indexJson = mapper.writeValueAsString(index) //企业自增编码json串
      val companyInfoJson = mapper.writeValueAsString(companyInfo) //企业信息串

      cominfo = cominfo.append(indexJson + "\n" + companyInfoJson) //json结果串
      cominfo.toString()
    })
    val path = new Path(outputPath) //创建文本输出路径
    val fs = FileSystem.get(URI.create(outputPath), conf)
    if (fs.exists(path)) {
      fs.delete(path, true)
    }
    result.coalesce(splitNum.toInt, true).saveAsTextFile(outputPath)
    sc.stop()
  }
}
